package br.com.toscano.gobra.view;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import br.com.toscano.gobra.business.LicencaBC;
import br.com.toscano.gobra.domain.Licenca;
import br.gov.frameworkdemoiselle.annotation.PreviousView;
import br.gov.frameworkdemoiselle.stereotype.ViewController;
import br.gov.frameworkdemoiselle.template.AbstractEditPageBean;
import br.gov.frameworkdemoiselle.transaction.Transactional;
import br.gov.frameworkdemoiselle.util.ResourceBundle;

@ViewController
@PreviousView("./index.jsf")
public class LicencaEditMB extends AbstractEditPageBean<Licenca, Long> {

	private static final long serialVersionUID = 1L;

	@Inject
	private ResourceBundle bundle;
	
	@Inject
	private FacesContext facesContext;
	
	@Inject
	private LicencaBC licencaBC;
	
	private String licenca;
	private String codigoSolicitacaoLicenca;
	
	@Override
	@Transactional
	public String delete() {
		this.licencaBC.delete(getId());
		return getPreviousView();
	}

	@Override
	@Transactional
	public String insert() {

		this.licencaBC.insert(licenca);
		String codigoValidacao = this.licencaBC.getCodigoValidadeLicenca();
		if ("".equals(codigoValidacao)){
			return getPreviousView();	
		} else {
			facesContext.addMessage("licenca", new FacesMessage(this.licencaBC.getDescricaoErro(codigoValidacao)));
			return getCurrentView();
		}
	}

	
	@Override
	@Transactional
	public String update() {
		this.licencaBC.update(getBean());
		return getPreviousView();
	}
	
	@Override
	protected Licenca handleLoad(Long id) {
		setBean(this.licencaBC.load(id));
		
		return this.getBean();
	}

	public String getLicenca() {
		return licenca;
	}

	public void setLicenca(String licenca) {
		this.licenca = licenca;
	}

	public String getCodigoSolicitacaoLicenca() {
		if (codigoSolicitacaoLicenca == null) {
			try {
				codigoSolicitacaoLicenca = licencaBC.gerarSolicitacaoLicenca();	
			} catch (Throwable e) {
				facesContext.addMessage("codigoSolicitacaoLicenca", new FacesMessage("ERRO: " + e.getMessage()));
			}
		}
		return codigoSolicitacaoLicenca;
	}

	public void setCodigoSolicitacaoLicenca(String codigoSolicitacaoLicenca) {
		this.codigoSolicitacaoLicenca = codigoSolicitacaoLicenca;
	}
}